package com.example.demo1122.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo1122.DTO.ChapterDTO;
import com.example.demo1122.DTO.StudentDTO;
import com.example.demo1122.domain.LoginAdmin;
import com.example.demo1122.domain.ResponseResult;
import com.example.demo1122.entity.*;
import com.example.demo1122.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.apache.logging.log4j.util.Strings.isEmpty;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IClassService classService;
    @Autowired
    private IChapterService chapterService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ICourseService courseService;

    private String fromTokenGetAdminID(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginAdmin loginAdmin = (LoginAdmin) authentication.getPrincipal();
        String adminID = loginAdmin.getAdmin().getAdminID();
        return adminID;
    }
    // 管理员修改自己的密码 已更新接口文档
    @PostMapping("/changePassword")
    @ResponseBody
    public ResponseResult changePassword(@RequestParam String newPassword) {
        return adminService.changePassword(newPassword);
    }

    // 管理员查看自己的信息
    @GetMapping("/profile")
    @ResponseBody
    public ResponseResult getProfile(){
        String adminID = fromTokenGetAdminID();
        System.out.println("管理员ID："+adminID);
        return adminService.getProfile(adminID);

    }
    //管理员将助教加入课堂 已更新接口文档
    @PostMapping("/saveTA")
    @ResponseBody
    public ResponseResult saveTA(@RequestParam String teacherName,
                                 @RequestParam String teacherID,
                                 @RequestParam Integer classID
    ) {
        try {

            // 新增或者更新
            return teacherService.addTAToClass(teacherID,teacherName,classID);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }

    //删除单个助教与课堂的连接数据 接口文档无需更新
    @DeleteMapping("/{classID}/{teacherID}")
    @ResponseBody
    public ResponseResult deleteta(@PathVariable Integer classID, @PathVariable String teacherID) {
        try {
            if(teacherID.equals(classService.getById(classID).getTeacherID())){//如果要删除的teacher是创建课堂的人，不能删除
                return new ResponseResult(157, "删除失败，不能删除创建课堂的老师");
            }
            boolean result = adminService.deleteTAFromClass(classID, teacherID);
            if(result) {
                return new ResponseResult(156, "删除成功");
            } else {
                return new ResponseResult(157, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(157, "删除失败，异常：" + e.getMessage());
        }
    }

    //管理员修改学生密码 20240102 20240102管理员controller新增
    //修改学生密码
    @PostMapping("/updatestudentpassword")
    @ResponseBody
    public ResponseResult updatepassword(@RequestBody Student student) {
        try {
            String password = "123456";
            if (!isEmpty(student.getPassword())){
                password =student.getPassword();
            }
            student.setPassword(passwordEncoder.encode(password));
            // 新增或者更新
            return studentService.updateStudentpassword(student);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }
    //管理员重置学生密码 20240311 20240102管理员controller新增
    //重置学生密码
    @PostMapping("/resetstudentpassword")
    @ResponseBody
    public ResponseResult resetpassword(@RequestParam String studentID) {
        try {
            String password = "123456";
            Student student=studentService.getById(studentID);
            student.setPassword(passwordEncoder.encode(password));
            // 新增或者更新
            return studentService.updateStudentpassword(student);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }
    //管理员只修改学生信息 20240102 20240102管理员controller新增
    @PostMapping("/updatestudentmassage")
    @ResponseBody
    public ResponseResult updatemassage(@RequestBody StudentDTO student) {

        try {
            // 新增或者更新
            return studentService.updateStudent(student);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }

    //管理员根据学生ID查询该学生加入的课堂 20240102 20240102管理员controller新增
    @GetMapping("/findalljoin/{studentID}")
    @ResponseBody
    public ResponseResult findAllclass(@PathVariable String studentID) {
        return studentService.findclassByStudentId(studentID);
    }

    // 管理员新增教师 20240102 20240102管理员controller新增
    @PostMapping("/save")
    @ResponseBody
    public ResponseResult save(@RequestBody Teacher teacher) {
        if(isEmpty(teacher.getPassword())) {
            teacher.setPassword("123456");
        }
        try {
            String password = passwordEncoder.encode(teacher.getPassword());
            teacher.setPassword(password);
            // 新增或者更新
            return teacherService.saveTeacher(teacher);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }
    //管理员修改教师信息 20240102 20240102管理员controller新增
    @PostMapping("/update")
    @ResponseBody
    public ResponseResult update(@RequestBody Teacher teacher) {
        try {
            Teacher teachertemp=teacherService.getById(teacher.getTeacherID());
            if(teacher.getName()==null){
                teacher.setName(teachertemp.getName());
            }
            if(teacher.getPassword()==null){
                teacher.setPassword(teachertemp.getPassword());
            }
            String password = passwordEncoder.encode(teacher.getPassword());
            teacher.setPassword(password);
            // 新增或者更新
            return teacherService.updateTeacher(teacher);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }

    //管理员重置教师密码
    @PostMapping("/resetteacherpassword")
    @ResponseBody
    public ResponseResult resetteacherpassword(@RequestParam String teacherID) {
        try {
            Teacher teacher=teacherService.getById(teacherID);
            teacher.setPassword(passwordEncoder.encode("123456"));
            // 新增或者更新
            return teacherService.updateTeacher(teacher);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }

    // 管理员根据教师ID查询该教师创建的课堂20240102管理员controller新增
    @GetMapping("/findallcreate/{teacherID}")
    @ResponseBody
    public ResponseResult findAllteachercreateclass(@PathVariable String teacherID) {
        return teacherService.findclassByTeacherId(teacherID);
    }
    //管理员根据教师ID查询该教师加入的课堂（包括创建与助教）20240102管理员controller新增
    @GetMapping("/findalljoinforteacher/{teacherID}")
    @ResponseBody
    public ResponseResult findAlljoinclass(@PathVariable String teacherID) {
        return teacherService.findjoinclassByTeacherId(teacherID);
    }


    //管理员查询课程
    // 分页查询
    @GetMapping("/course/page2")
    @ResponseBody
    public ResponseResult findPage2(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") Integer courseID,
                                    @RequestParam(defaultValue = "") String name) {
        try {
            Page<Course> page = courseService.findPage(new Page<>(pageNum, pageSize), courseID,name);

            return new ResponseResult<>(166, "查询成功", page.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(167, "查询失败");
        }
    }
//管理员查看所有课程
    @GetMapping("/findallcourse")
    @ResponseBody
    public List<Course> findAll() {
        return courseService.list();
    }

    //管理员添加章节
    @PostMapping("/savechapter")
    @ResponseBody
    public ResponseResult save(@RequestBody List<ChapterDTO> chapterDTOs,
                               @RequestParam String courseName) {
        try {
            Course course = new Course();
            course=courseService.findbyname(courseName);
            Integer courseID = course.getCourseID();
            return chapterService.saveChapter(chapterDTOs,courseID);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "插入失败", null);
        }
    }

    //管理员查看章节
    @PostMapping("/findchapter")
    @ResponseBody
    public ResponseResult save(@RequestParam Integer courseID) {
        try {
            return chapterService.findChapterByCourseID(courseID);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "查询失败", null);
        }
    }


}
